<template>
  <div class="view-container">

    <div class="main-content">

      <div class="list-container" style="padding-top: 0">

        <el-form :inline="true" :model="queryParams" class="filter-form-inline" label-position="right" size="small">

          <el-row :gutter="40" style="width: 100%;border-size:border-box">

            <el-col :lg="5" :xs="8">
              <el-form-item label="状态" style="width: 100%">
                <el-select v-model="queryParams.sellerFactorStatus" clearable style="width: 100%" placeholder="请选择状态">
                  <el-option label="全部" value="" />
                  <el-option v-for="item in sellerData.filter(a=>a.value !== '-3')" :key="item.value"
                    :label="item.label" :value="item.value" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :lg="5" :xs="8">
              <el-form-item label="商销客户名称" style="width: 100%">
                <el-input v-model="queryParams.keyWord" @change="handleChange" clearable placeholder="商销客户名称" />
              </el-form-item>
            </el-col>

            <el-col :lg="5" :xs="8">
              <el-form-item label="产品信息" style="width: 100%">
                <el-select v-model="queryParams.productId" filterable clearable style="width: 100%"
                  placeholder="请选择产品信息">
                  <el-option v-for="item in productList" :key="item.id" :label=" getProductName(item) "
                    :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :lg="5" :xs="8">
              <el-form-item label="负责销售职员" style="width: 100%">
                <el-select v-model="queryParams.headId" clearable style="width: 100%" placeholder="请选择负责销售职员">
                  <el-option v-for="item in headData" :key="item.id" :label="item.realName" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :lg="4" :xs="8">
              <el-form-item style="width: 100%">
                <div style="width: 260px;flex-shrink: 0">
                  <el-button size="small" class="border-btn" @click="handleReset">重置</el-button>
                  <el-button type="primary" size="small" class="main-btn" @click="handleSearch">搜索</el-button>
                </div>
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>

        <table-tools>
          <template #left>
            <el-button v-auth="{v:['crm:marketing:cooperation:businessAgreement:create']}" type="primary" size="small"
              @click="handleDialog">新建商业营销要素
            </el-button>
          </template>
        </table-tools>

        <table-view :cell-style="cellStyle" :data="tableData" border header-cell-class-name="table-header" size="medium"
          @sort-change="handlSort" @row-click="aloneClick">
          <el-table-column :min-width="160" :show-overflow-tooltip="true" header-align="center" label="编号"
            prop="sellerFactorNumber" />

          <el-table-column :min-width="160" :show-overflow-tooltip="true" header-align="center" label="商销客户名称"
            prop="sellerDetail.sellerName" />

          <el-table-column :min-width="160" :show-overflow-tooltip="true" header-align="center" label="产品通用名"
            prop="productInfoDetail.productPopularName" />

          <el-table-column :min-width="160" :show-overflow-tooltip="true" header-align="center" label="商品名"
            prop="productInfoDetail.productName" />

          <el-table-column :min-width="160" :show-overflow-tooltip="true" header-align="center" label="生产厂家"
            prop="productInfoDetail.producer" />

          <el-table-column :min-width="120" :show-overflow-tooltip="true" header-align="center" label="包装规格"
            prop="productInfoDetail.packSpecs" />

          <el-table-column :min-width="120" :show-overflow-tooltip="true" align="center" label="交易价(元)"
            prop="tradePrice" />

          <el-table-column :min-width="130" :show-overflow-tooltip="true" align="center" label="负责营销职员"
            prop="headName" />

          <el-table-column :min-width="120" :show-overflow-tooltip="true" align="center" label="创建时间" prop="createdAt">
            <template #default="{row}">
              {{ dateFormat("yyyy-mm-dd", row.createdAt) }}
            </template>
          </el-table-column>

          <el-table-column :min-width="140" :show-overflow-tooltip="true" align="center" label="状态"
            prop="terminalStatus">
            <template #default="{row}">
              <div style="line-height: 20px"> {{ getLabel('seller_factor_status', row?.SellerFactorStatus) }}</div>
              <!-- row.flowStatus == 'REFUSE' || row.flowStatus == 'REPEAL' ||  -->
              <div style="line-height: 20px" class="flow-status-color" v-if="row.flowStatus == 'REJECT_INITIATOR'">
                [驳回]
              </div>
              <div style="line-height: 20px" class="flow-status-color" v-if="row?.SellerFactorStatus === '2' ">
                <span v-if="row.flowStatus == 'DOING'">
                  [
                  <span v-if="row.processDefinitionKey === 'sellerFactorChange'">变更</span>
                  <span v-if="row.processDefinitionKey === 'sellerFactorBan'">作废</span>
                  {{getLabel('approval_result', row.flowStatus)}}

                  ]
                </span>
              </div>

            </template>
          </el-table-column>

          <el-table-column align="center" label="操作" :min-width="140">
            <template #default="{row}">

              <el-button type="text" @click="handlDelete(row.id)" v-auth="{v: ['crm:marketing:cooperation:businessAgreement:dele'],
              bool:row?.SellerFactorStatus === '-1' || row?.SellerFactorStatus === '-2'}">
                删除
              </el-button>

              <el-button type="text" @click="handleEdit(row,1)"
                v-auth="{v: ['crm:marketing:cooperation:businessAgreement:edit'],
              bool:row?.SellerFactorStatus === '-1' || row?.SellerFactorStatus === '-2' || row?.SellerFactorStatus === '-3'
              || row?.flowStatus === 'REJECT_INITIATOR'}">
                编辑
              </el-button>

              <template v-if="row?.SellerFactorStatus === '2' && row?.flowStatus !== 'DOING'">
                <el-button v-auth="{v: ['crm:marketing:cooperation:businessAgreement:change']}" type="text"
                  @click="handleEdit(row,2)">
                  变更
                </el-button>

                <el-button v-auth="{v: ['crm:marketing:cooperation:businessAgreement:invalid']}" type="text"
                  @click="handleInvalid(row)">
                  作废
                </el-button>
              </template>

            </template>
          </el-table-column>
        </table-view>
        <Pagination v-model:limit="queryParams.pageSize" v-model:page="queryParams.page" :total="total"
          style="display: flex; justify-content: flex-end" @pagination="handlList" />

      </div>

    </div>

    <newForm ref="newFormRef" :typeEdit="typeEdit" @succsess="succsess" />

    <invalid ref="invalidRef" @succsessBan="succsessBan" />
  </div>
</template>

<script>
import {
  defineAsyncComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  toRefs,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import { crmStore } from "@CRM/store";

export default {
  components: {
    newForm: defineAsyncComponent(() => import("../modules/newForm.vue")),
    invalid: defineAsyncComponent(() => import("../modules/invalid.vue")),
  },
  setup() {
    const api = inject("api");
    const router = useRouter();
    const route = useRoute();
    const currentInstance = getCurrentInstance();
    const data = reactive({
      queryParams: {
        sellerFactorStatus: "",
        keyWord: "",
        headId: undefined,
        productId: undefined,
        pageSize: 20,
        page: 1,
      },
      total: 0,
      tableData: [{ id: 2 }],
      productList: [],
      sellerData:
        crmStore.getters["dictionary/getDictionary"]["seller_factor_status"] ||
        [],
      headData: crmStore.getters["company/getHeadOptions"] || [],
      newFormRef: null,
      typeEdit: "create",
      invalidRef: null,
    });

    const handleProductList = () => {
      api.businessAgreement.BUSINESSAGREEMENT_PRODUCT(1).then((res) => {
        if (res.code === 0) {
          data.productList = res.data.data || [];
        }
      });
    };

    // 获取列表
    const handlList = () => {
      api.businessAgreement
        .BUSINESSAGREEMENT_LIST(data.queryParams)
        .then((res) => {
          if (res.code === 0) {
            data.tableData = res.data.list || [];
            data.total = res.data.total;
          }
        });
    };

    const handleReset = () => {
      data.queryParams = {
        sellerFactorStatus: "",
        keyWord: "",
        headId: undefined,
        productId: undefined,
        pageSize: 20,
        page: 1,
      };
      handlList();
    };

    const handleSearch = () => {
      data.queryParams.page = 1;
      handlList();
    };

    // 单机表格
    const aloneClick = (row, column, event) => {
      if (column.label === "操作" || column.label === "查看文件") return;
      router.push({
        name: "businessAgreementDetail",
        query: { id: row.id },
      });
    };

    // 鼠标样式
    const cellStyle = () => {
      return "cursor:pointer;";
    };

    //删除
    const handlDelete = (id) => {
      currentInstance.proxy
        .alertBox({ message: "删除数据后不可恢复,确定删除？" })
        .then(() => {
          api.businessAgreement.BUSINESSAGREEMENT_DELETE(id).then((res) => {
            if (res.code === 0) {
              currentInstance.proxy.customMessage({
                type: "success",
                message: "删除成功",
              });
              handlList();
            } else {
              currentInstance.proxy.customMessage({
                type: "error",
                message: res.msg,
              });
            }
          });
        })
        .catch((err) => {
          console.log(err);
        });
    };

    //作废
    const handleInvalid = (row) => {
      data.invalidRef.open(row);
    };

    //打开弹框
    const handleDialog = () => {
      var title = "新建商业营销要素";
      data.typeEdit = "create";
      data.newFormRef.open(title, null);
    };

    //编辑
    const handleEdit = (val, num) => {
      var title = "";
      if (num === 1) {
        title = "编辑商业营销要素";
        data.typeEdit = "create";
      }
      if (num === 2) {
        title = "变更商业营销要素";
        data.typeEdit = "change";
      }
      data.newFormRef.open(title, val);
    };

    const succsess = () => {
      handlList();
    };

    const succsessBan = () => {
      handlList();
    };

    onMounted(() => {
      handleProductList();
      handlList();
    });

    return {
      ...toRefs(data),
      handleProductList,
      handlList,
      handleReset,
      handleSearch,
      aloneClick,
      cellStyle,
      handlDelete,
      handleInvalid,
      handleDialog,
      handleEdit,
      succsess,
      succsessBan,
    };
  },
};
</script>

<style lang="scss" scoped>
</style>
